﻿using System;
using System.Security.Cryptography;
using System.Text;
using DiplomaWeb.Utils.PasswordsUtils;

namespace Diploma.Models.Utils.PasswordsUtils
{
    public static class PasswordGenerator
    {
        private const string Upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        private const string Lower = "abcdefghijklmnopqrstuvwxyz";
        private const string Numbers = "0123456789";
        private const string Symbols = "~`!@#$%^&*()_+=-{[}]|;:'<,>.?";
        private static readonly RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

        public static string GeneratePassword()
        {
            return GeneratePassword(true, true, true, false, 8);
        }

        private static string GeneratePassword(bool useUpper, bool userLower, bool userNumbers, bool useSymbols,
                                               int passwordLength)
        {
            var charPool = new StringBuilder();
            var newPass = new StringBuilder();

            if (useUpper)
                charPool.Append(Upper);

            if (userLower)
                charPool.Append(Lower);

            if (userNumbers)
                charPool.Append(Numbers);

            if (useSymbols)
                charPool.Append(Symbols);

            int max = charPool.Length - 1;
            var random = new Byte[passwordLength];
            rng.GetBytes(random);

            for (int x = 0; x < passwordLength; x++)
            {
                while (random[x] > max)
                    random[x] = (byte) Math.Abs(random[x] - max/2);
                newPass.Append(charPool[random[x]]);
            }
            return newPass.ToString();
        }

        public static string Encrypt(string password)
        {
            password = password.Trim();
            IPasswordsUtil passwordUtil = new SimplePasswordUtil();
            string encryptedPassword = passwordUtil.EncryptPassword(password);

            return encryptedPassword;
        }
    }
}